const gulp = require("gulp")
const path = require("path")
const through2 = require("through2")
const fs = require("fs")

const assetsDir = "/src/assets"
const fontDir = "./src/assets/fonts/**/*"
const imgsDir = "./src/assets/imgs/**/*"
const outputFile = "./src/assetsConfig.ts"

const imgCache = {}
const fontCache = {}

function camelizeKey(key, separators = ['-', '_']) {
  const out = []
  let i = 0
  while (i < key.length) {
    if (separators.indexOf(key[i]) > -1) {
      out.push(key[i + 1].toUpperCase())
      i++
    } else {
      out.push(key[i])
    }
    i++
  }
  return out.join('')
}

function compileImgFile() {
  const importList = []
  const exportObj = {}
  return gulp.src(imgsDir)
    .pipe(through2.obj(function (file, enc, callback) {
      const [path, ext] = file.relative.split(".")
      if (!ext) {
        return callback()
      }
      const [rawDirName, rawFileName] = path.split("/")
      const name = camelizeKey(rawFileName)
      const dirName = camelizeKey(rawDirName)
      const val = `import * as ${name} from '@assets/imgs/${path}.${ext}'`
      exportObj[dirName] = []
      if (!imgCache[name]
        || imgCache[name].dirName !== dirName
        || imgCache[name].val !== val) {
        imgCache[name] = {
          dirName, val
        }
      }
      return callback()
    }, function (callback) {
      for (let name in imgCache) {
        const { dirName, val } = imgCache[name]
        importList.push(val)
        if (new Set(exportObj[dirName]).has(name)) {
          continue
        }
        exportObj[dirName].push(name)
      }
      const exportList = []
      for (let dirName in exportObj) {
        exportList.push(`
export const ${dirName} = {
  ${exportObj[dirName].join(", ")}
}`)
      }
      const output = `
// NOTE: 这个文件的内容自动生成！请不要编辑；
${importList.join("\n")}
${exportList.join("\n")}
`
      fs.writeFileSync(outputFile, output)
      return callback()
    }))
}


function watchCompile() {
  return gulp.watch(path.join(__dirname, assetsDir, "/**/*"), gulp.series(["compileFile"]))
};

gulp.task("watchCompile", watchCompile)

gulp.task("compileFile", compileImgFile)

// 如果定义了 default 任务， 那么不管运行那个任务都会在最后运行这个任务
gulp.task('default', gulp.series(["compileFile", "watchCompile"]));
